function [centers, semiAxes, angles] = ellipsecoef2par(coef) %#codegen
%ELLIPSECOEF2PAR 根据椭圆方程系数计算椭圆圆心、长半轴短半轴、倾斜角
%
% Input Arguments
% # coef：m*6矩阵，椭圆方程系数，n表示椭圆方程个数
%
% Output Arguments
% # centers：m*2矩阵，椭圆圆心
% # semiAxes：m*2矩阵，椭圆长半轴和短半轴
% # angles：长度为m的列向量，椭圆倾斜角，长半轴与x轴夹角，单位：弧度
%
% Reference
% # 李良福 冯祖人 贺凯良：一种基于随机Hough变换的椭圆检测算法研究

m = size(coef, 1);
centers = NaN(m, 2);
semiAxes = NaN(m, 2);
angles = NaN(m, 1);

for i = 1:m
    angles(i) = 0.5 * atan(coef(i, 2)/(coef(i, 1)-coef(i, 3)));
    A = coef(i, 1);
    B = coef(i, 2);
    C = coef(i, 3);
    D = coef(i, 4);
    E = coef(i, 5);
    F = coef(i, 6);
    
    centers(i, 1) = (B*E - 2*C*D) / (4*A*C - B*B); % 圆心计算部分论文公式错误
    centers(i, 2) = (B*D - 2*A*E) / (4*A*C - B*B);
    
    m1 = A*(cos(angles(i)))^2 + B*sin(angles(i))*cos(angles(i)) + C*sin((angles(i)))^2;
    n1 = D*cos(angles(i)) + E * sin(angles(i));
    m2 = A*sin((angles(i)))^2 - B*sin(angles(i))*cos(angles(i)) + C*cos((angles(i)))^2;
    n2 = -D*sin(angles(i)) + E * cos(angles(i));
    
    semiAxes(i, 1) = sqrt((m2*n1^2 + m1*n2^2 -4*m1*m2*F) / (4*m1^2*m2));
    semiAxes(i, 2) = sqrt((m2*n1^2 + m1*n2^2 -4*m1*m2*F) / (4*m1*m2^2));
    
    if semiAxes(i, 1) < semiAxes(i, 2)
        tmp = semiAxes(i, 1);
        semiAxes(i, 1) = semiAxes(i, 2);
        semiAxes(i, 2) = tmp;
        angles(i) = angles(i) + 90/180*pi;
    end
end
end